package cn.itsource.pethome.user.service.impl;

import cn.itsource.pethome.base.util.AjaxResult;
import cn.itsource.pethome.base.util.MD5Utils;
import cn.itsource.pethome.user.domain.LoginInfo;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.mapper.LoginInfoMapper;
import cn.itsource.pethome.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult login(UserDto userDto) {
        //校验前端传递数据
        LoginInfo loginInfo = checkUserDto(userDto);
        //随机产生token值
        String token = UUID.randomUUID().toString();
        //类似于session的机制，把登录用户对象存储起来
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        //向前端服务返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("loginUser", loginInfo);
        return new AjaxResult().setResultObj(map);
    }

    private LoginInfo checkUserDto(UserDto userDto) {
        if(StringUtils.isEmpty(userDto.getUsername())||
                StringUtils.isEmpty(userDto.getPassword())
                ||userDto.getType()==null){
            throw new RuntimeException("请完善登录信息!!");
        }
        //通过用户名在t_logininfo中查找是否有对应的数据 （用户名和状态）
        LoginInfo loginInfo = loginInfoMapper.loadByUserDto(userDto);
        if(loginInfo == null){
            throw new RuntimeException("用户名不存在!!");
        }
        //判断账号是否禁用了
        if(!loginInfo.getDisable()){
            throw new RuntimeException("该账号已被禁用，请联系管理人员!!");
        }
        //判断密码
        if(!loginInfo.getPassword().equals(
                MD5Utils.encrypByMd5(userDto.getPassword()+loginInfo.getSalt()))){
            throw new RuntimeException("登录密码错误!!");
        }
        return loginInfo;
    }
}
